package com.example.spring_project.controller;

import com.example.spring_project.entity.Book;
import com.example.spring_project.service.BookService;
import com.example.spring_project.utils.Dateutil;
import com.example.spring_project.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.*;


@RestController
@RequestMapping("/book")
@Api(value = "图书管理", tags = {"图书管理接口"})
public class BookController {
    private final BookService bookService;
    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/books")
    @ApiOperation(value = "获取所有图书列表", notes = "获取所有图书列表。")
    public List<Book> listBooks(){
        return bookService.list();
    }
    @GetMapping("/get")
    @ApiOperation(value = "根据图书ID获取图书信息", notes = "根据图书ID获取图书信息。")
    public Book getById(@RequestParam @ApiParam(value = "图书ID",example = "1") int id){
        return bookService.getById(id);
    }
    @PostMapping("/add")
    @ApiOperation(value = "添加图书", notes = "添加图书。")
    public String  add(@RequestParam @ApiParam(value = "图书作者") String author,
                       @RequestParam @ApiParam(value = "库存数量") int stock,
                       @RequestParam @ApiParam(value = "图书名称") String name,
                       @RequestParam @ApiParam(value = "出版日期") String date){/*@PathVariable String publish_date*/
        final Book book = new Book();
        Dateutil dateutil = new Dateutil();
        Date sqlDate = dateutil.StringToDate(date);
        book.setBookAuthor(author);
        book.setBookName(name);
        book.setInStock(stock);
        book.setPublishDate(sqlDate);
        bookService.save(book);
        return "ok";
    }
    @DeleteMapping("/delete")
    @ApiOperation(value = "根据图书ID删除图书", notes = "根据图书ID删除图书。")
    public String deleteById(@RequestParam @ApiParam(value = "图书ID", example = "1") int id){
        if (bookService.deleteById(id)){
            return "ok";
        }else {
            return "删除失败";
        }
    }
    @PutMapping("/update")
    @ApiOperation(value = "根据图书ID更新图书库存", notes = "根据图书ID更新图书库存。")
    // 管理员与消费者公用一个controller，此处应注意，后续更改
    public Result<Object> updateStockByid(@RequestParam @ApiParam(value = "图书ID", example = "1") int id, @RequestParam @ApiParam(value = "库存数量") int stock){
        return bookService.updateById(id,stock);
    }
}
